package com.vanzo.tisen.agingtest.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.vanzo.tisen.agingtest.AgingApplication;
import com.vanzo.tisen.agingtest.Anticlockwise;
import com.vanzo.tisen.agingtest.DeviceException;
import com.vanzo.tisen.agingtest.SharedString;
import com.vanzo.tisen.agingtest.test.CameraTest;
import com.vanzo.tisen.agingtest.test.DeviceTest;
import com.vanzo.tisen.agingtest.test.FrontCameraTest;
import com.vanzo.tisen.agingtest.test.HandsetTest;
import com.vanzo.tisen.agingtest.test.LcdTest;
import com.vanzo.tisen.agingtest.test.MicTest;
import com.vanzo.tisen.agingtest.R;
import com.vanzo.tisen.agingtest.test.RebootTest;
import com.vanzo.tisen.agingtest.test.SpeakerTest;
import com.vanzo.tisen.agingtest.test.VibratorTest;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/3/9.
 */

public class AgingTesting extends Activity {
    public static int RESULT_CODE = 0;

    private AgingApplication agingApplication;
    private ArrayList<String> devices = new ArrayList<>();
    private ArrayList<DeviceTest> deviceTests = new ArrayList<>();
    private int count = 0;
    private DeviceTest deviceTest;
    private Timer timer = new Timer();
    private TextView testingText;
    private Anticlockwise chronometer;
    private LinearLayout layout;
    private long[] pattern = {500, 500, 500, 500, 500, 1500};
    private String path;
    private long duration;
    private long durationAll;

    private Handler testing = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (deviceTest != null) {
                deviceTest.stop();
                count++;
                count = count % devices.size();
            }
            deviceTest = deviceTests.get(count);
            try {
                deviceTest.start();
            } catch (DeviceException e) {
                e.printStackTrace();
                testFailed(e);
            }
            testingText.setText(deviceTest.getName());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.agingtest_main);
        agingApplication = (AgingApplication) getApplication();
        testingText = (TextView) findViewById(R.id.testing);
        chronometer = (Anticlockwise) findViewById(R.id.chronometer);
        layout = (LinearLayout) findViewById(R.id.linear_layout);

        path = "android.resource://" + getPackageName() + "/" + R.raw.sherlock;


        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        Intent intent = getIntent();
        duration = intent.getIntExtra("duration", 20) * 1000;
        durationAll = intent.getIntExtra("durationAll", 120) * 60;
        devices = intent.getStringArrayListExtra("devices");
        for (String s :
                devices) {
            DeviceTest deviceTest = null;
            switch (s) {
                case "reboot":
                    agingApplication.setDeviceTest(SharedString.IS_REBOOT, true);
                    deviceTest = new RebootTest(this, new RebootTest.RebootListener() {
                        @Override
                        public void onReboot() {
                            agingApplication.setAgingRunning(true);
                            agingApplication.setHasReboot(true);
                            agingApplication.setAgingTime(chronometer.getNextTime()/60);
                            agingApplication.setRoundTime(duration/1000);
                        }
                    });
                    break;
                case "lcd":
                    agingApplication.setDeviceTest(SharedString.IS_LCD, true);
                    deviceTest = new LcdTest(this, testingText);
                    break;
                case "speaker":
                    agingApplication.setDeviceTest(SharedString.IS_SPEAKER, true);
                    deviceTest = new SpeakerTest(this, path);
                    break;
                case "vibrator":
                    agingApplication.setDeviceTest(SharedString.IS_VIBRATOR, true);
                    deviceTest = new VibratorTest(this, pattern);
                    break;
                case "mic":
                    agingApplication.setDeviceTest(SharedString.IS_MIC, true);
                    deviceTest = new MicTest();
                    break;
                case "handset":
                    agingApplication.setDeviceTest(SharedString.IS_HANDSET, true);
                    deviceTest = new HandsetTest(this, path);
                    break;
                case "camera":
                    agingApplication.setDeviceTest(SharedString.IS_CAMERA, true);
                    deviceTest = new CameraTest(this, layout);
                    break;
                case "forntcamera":
                    agingApplication.setDeviceTest(SharedString.IS_FRONT_CAMERA, true);
                    deviceTest = new FrontCameraTest(this, layout);
                    break;
                default:
                    break;
            }
            if (deviceTest != null)
                deviceTests.add(deviceTest);
        }
        chronometer.setBase(SystemClock.elapsedRealtime());
        chronometer.initTime(durationAll);
//        int hour = (int) ((SystemClock.elapsedRealtime()-chronometer.getBase())/1000/60);
//        chronometer.setFormat("0"+String.valueOf(hour)+":%s");
        chronometer.setOnTimeCompleteListener(listener);
        chronometer.start();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                testing.sendEmptyMessage(1);
            }
        }, 0, duration);
    }

    private Anticlockwise.OnTimeCompleteListener listener = new Anticlockwise.OnTimeCompleteListener() {
        @Override
        public void onTimeComplete() {
            testComplete();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        agingApplication.setAgingTime(chronometer.getNextTime()/60);
        agingApplication.setRoundTime(duration/1000);
        deviceTest.stop();
    }

    //    private void error(PermissionException e){
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setMessage(e.toast());
//        builder.setTitle("权限错误");
//        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                Intent localIntent = new Intent();
//                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                if (Build.VERSION.SDK_INT >= 9) {
//                    localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
//                    localIntent.setData(Uri.fromParts("package", getPackageName(), null));
//                } else if (Build.VERSION.SDK_INT <= 8) {
//                    localIntent.setAction(Intent.ACTION_VIEW);
//                    localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
//                    localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
//                }
//                startActivity(localIntent);
//                finish();
//            }
//        });
//        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                finish();
//            }
//        });
//        builder.create().show();
//    }
    private void testComplete() {
        Toast.makeText(this, getResources().getString(R.string.agingtest_complete), Toast.LENGTH_LONG).show();
        agingApplication.setAgingRunning(false);
        Intent intent = new Intent();
        intent.putExtra("result", true);
        setResult(RESULT_CODE, intent);
        finish();
    }

    private void testFailed(DeviceException e) {
        Toast.makeText(this, e.toast(), Toast.LENGTH_LONG).show();
        agingApplication.setAgingRunning(false);
        Intent intent = new Intent();
        intent.putExtra("result", false);
        setResult(RESULT_CODE, intent);
        finish();
    }
}
